//
//  AppDelegate.m
//  Tunnel
//
//  Created by wbb on 2022/3/7.
//

#import "AppDelegate.h"
#import "JPUSHService.h"
#import "YJXYDetailVC.h"
#import "GZGJDetailVC.h"
#import "JKGJDetailVC.h"
#import "YXJCDetailVC.h"
#import "VideoDetailVC.h"
#import "AQJCDetailVC.h"
#import "MessageViewController.h"
#import <UserNotifications/UserNotifications.h>
#import "AppDelegate+Extension.h"

@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   
    
    [self registerJpush:launchOptions];
    /// 设置根控制器
    [self setWindowAndRootViewController];
    [self getUnReadNum];
    return YES;
}
-(void)registerJpush:(NSDictionary *)launchOptions{
    
    
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|
    JPAuthorizationOptionBadge|
    JPAuthorizationOptionSound|
    JPAuthorizationOptionProvidesAppNotificationSettings;
    
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    //修改appkey
    [JPUSHService setupWithOption:launchOptions
                           appKey:@"da7ed7dfb751cf0e8dd7d5a3"
                          channel:@"App Store"
                 apsForProduction:true advertisingIdentifier:nil];
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidSetup:) name:kJPFNetworkDidSetupNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(networkDidClose:) name:kJPFNetworkDidCloseNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(networkDidRegister:) name:kJPFNetworkDidRegisterNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(networkDidLogin:) name:kJPFNetworkDidLoginNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
}
- (void)application:(UIApplication*)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
    
    //sdk注册DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    
}
#pragma mark - 极光推送
- (void)networkDidSetup:(NSNotification *)notification {
    NSLog(@"\n\n\n已连接...\n\n\n");
}

- (void)networkDidClose:(NSNotification *)notification {
    NSLog(@"\n\n\n未连接...\n\n\n");
}

- (void)networkDidRegister:(NSNotification *)notification {
    NSLog(@"\n\n\n已注册...\n\n\n");
}

- (void)networkDidLogin:(NSNotification *)notification {
    NSLog(@"\n\n\n已登录...\n\n\n");
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        NSLog(@"resCode : %d,registrationID: %@",resCode,registrationID);
    }];
}

- (void)networkDidReceiveMessage:(NSNotification *)notification {
    
    NSLog(@"networkDidReceiveMessage==%@",notification.userInfo);
    
}

-(void)resloveNotification:(NSDictionary*)userInfo{
    
    NSLog(@"推送消息%@",userInfo);
    NSString * bizId = [NSString stringWithFormat:@"%@",userInfo[@"bizId"]];
    NSString * msgType = [NSString stringWithFormat:@"%@",userInfo[@"msgType"]];
    NSString * msgId = [NSString stringWithFormat:@"%@",userInfo[@"msgId"]];

    if([msgType isEqualToString:@"EMERGENCECREATION"]){
        YJXYDetailVC * vc = [YJXYDetailVC new];
        vc.ID = bizId;
        [[WDGlobal getCurrentViewController].navigationController pushViewController:vc animated:NO];
    }else if ([msgType isEqualToString:@"PLC_FAULT_ALARMS"]) {
        GZGJDetailVC * vc = [GZGJDetailVC new];
        vc.gjId = bizId;
        vc.lx = @"1";
        [[WDGlobal getCurrentViewController].navigationController pushViewController:vc animated:NO];
    }else if ([msgType isEqualToString:@"THRESHOLD_MONITORING_ALARMS"]) {
        JKGJDetailVC * vc = [JKGJDetailVC new];
        vc.jkId = bizId;
        [[WDGlobal getCurrentViewController].navigationController pushViewController:vc animated:NO];
    }else if ([msgType isEqualToString:@"THE_DEVICE_IS_OFFLINE"]) {
        YXJCDetailVC * vc = [YXJCDetailVC new];
        vc.ID = bizId;
        [[WDGlobal getCurrentViewController].navigationController pushViewController:vc animated:NO];
    }else if ([msgType isEqualToString:@"SECURITYREVIEW"]) {
        AQJCDetailVC * vc = [AQJCDetailVC new];
        vc.ID = bizId;
        [[WDGlobal getCurrentViewController].navigationController pushViewController:vc animated:NO];
    }else if ([msgType isEqualToString:@"NON_MOTORIZED_VEHICLE_BREAK_IN"] || [msgType isEqualToString:@"PEDESTRIAN_TRESPASSING"] || [msgType isEqualToString:@"SCATTERED_OBJECTS"] || [msgType isEqualToString:@"WORK_CAR"]) {
        
        //视频监控
        VideoDetailVC *vc = [[VideoDetailVC alloc] init];
        vc.isShowHistory = NO;
        vc.isHeight = NO;
        vc.ID = bizId;
        [[WDGlobal getCurrentViewController].navigationController pushViewController:vc animated:NO];
    }else if ([msgType isEqualToString:@"MULTI_VEHICLE_ACCIDENTS"] || [msgType isEqualToString:@"BICYCLE_PARKING"] || [msgType isEqualToString:@"RETROGRADE"] || [msgType isEqualToString:@"LANE_CHANGES_IN_VIOLATION_OF_REGULATIONS"] || [msgType isEqualToString:@"CRIMPING"] || [msgType isEqualToString:@"OCCUPY_A_DEDICATED_LANE"] || [msgType isEqualToString:@"TRAFFIC_CONGESTION"] ){
        
        //视频监控
        VideoDetailVC *vc = [[VideoDetailVC alloc] init];
        vc.isShowHistory = YES;
        vc.isHeight = NO;
        vc.ID = bizId;
        [[WDGlobal getCurrentViewController].navigationController pushViewController:vc animated:NO];
    }else if ([msgType isEqualToString:@"FOCUS_ON_VEHICLES"] ){// 超高
        //视频监控
        
        VideoDetailVC *vc = [[VideoDetailVC alloc] init];
        vc.ID = bizId;
        vc.isShowHistory = NO;
        vc.isHeight = YES;
        [[WDGlobal getCurrentViewController].navigationController pushViewController:vc animated:NO];
    }else{
        [WDGlobal getCurrentViewController].tabBarController.selectedIndex = 1;
    }
    kWEAK_SELF;
    [TYNetWorkTool getRequest:[NSString stringWithFormat:@"%@%@",TYGetMsgRead,msgId] parameters:@{} successBlock:^(BOOL success, id  _Nonnull data, NSString * _Nonnull msg) {
        // 进入DispatchGroup，表示开始一个任务
        NSLog(@"-------1111-----------");
        if(success) {
            // 进详情
            
        }
        
    } failureBlock:^(NSString * _Nonnull description) {
        // 进入DispatchGroup，表示开始一个任务
        
    }];
}
- (void)jpushNotificationAuthorization:(JPAuthorizationStatus)status withInfo:(nullable NSDictionary *)info {
    
}

- (void)jpushNotificationCenter:(nonnull UNUserNotificationCenter *)center didReceiveNotificationResponse:(nonnull UNNotificationResponse *)response withCompletionHandler:(nonnull void (^)(void))completionHandler { 
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    [self resloveNotification:userInfo];
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)jpushNotificationCenter:(nonnull UNUserNotificationCenter *)center openSettingsForNotification:(nonnull UNNotification *)notification { 
    if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
      //从通知界面直接进入应用
    }else{
      //从通知设置界面进入应用
    }
}

- (void)jpushNotificationCenter:(nonnull UNUserNotificationCenter *)center willPresentNotification:(nonnull UNNotification *)notification withCompletionHandler:(nonnull void (^)(NSInteger))completionHandler { 
    // Required@property (nonatomic,strong) AVAudioPlayer *player; //播放提示音

    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    if (@available(iOS 14.0, *)) {
        completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBanner);
    } else {
        completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionList | UNNotificationPresentationOptionBanner);
        // Fallback on earlier versions
    } // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"注册远程通知失败：%@", error.localizedDescription);
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    application.applicationIconBadgeNumber = 0;
}
-(void)getUnReadNum{
    kWEAK_SELF;
    [TYNetWorkTool postRequest:TYGetMsg parameters:@{
        @"notifyChannel":@"APP",
        @"pageNum": @1,
        @"pageSize": @1
    } successBlock:^(BOOL success, id  _Nonnull data, NSString * _Nonnull msg) {
        // 进入DispatchGroup，表示开始一个任务
        NSLog(@"-------1111-----------");
        if(success) {
            NSInteger unReadNum = [data[@"data"][@"unReadNum"] intValue];
            UITabBarController * root = [WDGlobal getCurrentViewController].tabBarController; // self当前的viewController
            UITabBarItem * tabBarItem = [UITabBarItem new];
            if (root.tabBar.items.count>2) {
                tabBarItem = root.tabBar.items[1];// 拿到需要设置角标的tabarItem
            }
             
             
             
            if (unReadNum == 0) {
                [tabBarItem setBadgeValue:nil];// 隐藏角标
            }else if (unReadNum > 99) {
                [tabBarItem setBadgeValue:@"99+"];
                 
            } else {
                NSString *rst = [NSString stringWithFormat:@"%ld",(long)unReadNum];

                [tabBarItem setBadgeValue:rst];
                 
            }
            
        }
    } failureBlock:^(NSString * _Nonnull description) {
    }];
}

@end
